// pages/sellBook/sellBook.js

import {
  request
} from "../../request/index.js";

Page({

  /**
   * 页面的初始数据
   */
  data: {
    price: 0,
    index: 0,
    book_name: '',
    book_img: [],
    sellerId: 0,
    level: 0,
    bid: 0,
    cover: '',
    Degree: '',
    notes: '',
    edition: '',
    desc: '',
  },

  // 跳回首页
  jmp_index() {
    wx.navigateBack({
    })
  },
  // 发给买家
  sendMessageToBuyer(tradeNo) {
    var phone = wx.getStorageSync('userPhone')
    var address = wx.getStorageSync('add')
    request({
      url: "/message/messageToBuyer",
      method: "POST",
      data: {
        "address": address,
        "bookName": this.data.book_name,
        "phoneNum": phone,
        "tradeNo": tradeNo
      },
    })
      .then(result => {
        console.log('963')
        console.log(result)
      })
  },
  // 发给卖家
  sendMessageToSeller(tradeNo) {
    request({
      url: "/message/messageToSeller",
      method: "POST",
      data: {
        "bookName": this.data.book_name,
        "sellerId": this.data.sellerId,
        "tradeNo": tradeNo
      }
    })
      .then(result => {
        console.log('960')
        console.log(result)
      })
  },
  // 付款申请
  jmp_pay() {
    console.log("dianji...")
    const that = this
    if (wx.getStorageSync('userPhone') && wx.getStorageSync('add')) {
      console.log("jinlaile")
      // 调接口下单
      request({
        url: '/order/takeOneOrder',
        method: "POST",
        data: {
          // 下面以分为单位的
          "bookDealPrice": that.data.price,
          "bookWarehouseId": that.data.bid,
          "sellerId": that.data.sellerId,
        }
      })
        .then(result => {
          console.log(result)
          const errTips = result.data.message
          // 接口下单失败
          if (result.data.code != 20000) {
            wx.showToast({
              title: errTips,
              icon: 'error',
              duration: 2000
            })
            setTimeout(()=>{
              wx.redirectTo({
                url: '../../pages/index/index'
              })
            },2000)
            
          }
          // 接口下单成功 调微信付款
          else{
            wx.requestPayment({
              timeStamp: result.data.data.data.timeStamp,
              nonceStr: result.data.data.data.nonceStr,
              package: result.data.data.data.package,
              signType: 'RSA',
              paySign: result.data.data.data.paySign,
              // 付款成功
              success(res) {
                console.log(res)
                  wx.requestSubscribeMessage({
                    tmplIds: ['Hpjd0alVWAqSfwMX9mMFqh5AMubFrFLyEvPKmzefA6s'],
                    success(res) {
                      console.log(res)
                      that.sendMessageToBuyer(result.data.data.outTradeNo)
                      that.sendMessageToSeller(result.data.data.outTradeNo)
                    }
                  })
                  request({ 
                    url: 'order/paySuccess',
                    method: "POST",
                    data:
                      {
                        "bookDealPrice": that.data.price,
                        "bookWarehouseId": that.data.bid,
                        "outTradeNo": result.data.data.outTradeNo,
                        "sellerId": that.data.sellerId
                      }
                   })
                   .then(result1=>{
                     console.log(result1)
                     wx.redirectTo({
                      url: '../../pages/buy/buy'
                    })
                   })
                  console.log(' paySuccess ')
              },
              // 付款失败
              fail(err) {
                console.log(err)
                request({ 
                  url: '/order/payCancel',
                  method: "POST",
                  data:{
                    outTradeNo: result.data.data.outTradeNo,
                    bid: that.data.bid
                  }
                })
                .then(result=>{
                  console.log(result)
                  console.log(' payCancel ')
                })
              }
            })
          }
        })
        .catch(error=>{
          console.log("error")
          console.log(error)
        })
    }
    else {
      wx.showToast({
        title: '个人信息仍需完善噢',
        icon: 'none',
        duration: 1000
      })
    }

  
  },
  // 记录index
  markIndex(e) {
    this.setData({
      index: e.detail.current
    })
    // console.log(e)
  },

  // 放大照片
  large(e) {
    console.log(e)
    this.setData({
    })
    wx.previewImage({
      current: this.data.book_img[this.data.index],
      urls: this.data.book_img,
      success: (result) => { },
      fail: () => { },
      complete: () => { }
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    var that = this
    console.log(options)
    this.setData({
      bid: options.bid
    })
    // 获取数据
    request({
      url: `/book/index/sellingBook/${options.bid}`
    })
      .then(result => {
        let arr = []
        arr.push(result.data.data.book.bookCoverUrl)
        let a = JSON.parse(result.data.data.book.bookPhotoUrls)
        console.log(a);
        if(a instanceof Array){
          a.forEach(item=>{
            arr.push(item)
          })
        }
        console.log(result);
        that.setData({
          book_name: result.data.data.book.bookName,
          price: result.data.data.book.bookPrice,
          book_img: arr,
          sellerId: result.data.data.book.sellerId,
          cover: result.data.data.book.coverLevel,
          Degree: result.data.data.book.injureLevel,
          edition: result.data.data.book.bookVersion,
          notes: result.data.data.book.noteLevel,
          desc: result.data.data.book.bookDesc,
        })

      }).catch(err => {
        console.log(err)
      })
    console.log(that.data.book_img)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})